package com.zengyan.gd.controller;

import com.zengyan.gd.core.Result;
import com.zengyan.gd.core.ResultGenerator;
import com.zengyan.gd.core.ServiceException;
import com.zengyan.gd.form.MemberForm;
import com.zengyan.gd.form.OrgLoginForm;
import com.zengyan.gd.form.UpdateOrgForm;
import com.zengyan.gd.model.Event;
import com.zengyan.gd.model.Organization;
import com.zengyan.gd.model.User;
import com.zengyan.gd.service.OrganizationService;
import com.zengyan.gd.utils.ExcelUtils;
import com.zengyan.gd.utils.ImageUtils;

import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

import javax.validation.Valid;

@RestController
@RequestMapping("/org")
public class OrgController {


    @Autowired
    OrganizationService mOrgService;

    /**
     * @api {get}  /org/list  获取组织全部列表
     * @apiVersion 0.0.1
     * @apiGroup org
     */
    @GetMapping("/list")
    public Result getOrgList() throws Exception {
        List<Organization> list = mOrgService.findAllOrgs();
        return ResultGenerator.genSuccessResult(list);
    }


    /**
     * @api {post}  /org/register   组织注册
     * @apiGroup org
     * @apiVersion 0.0.1
     * @apiExample json
     * {
     * "description": "",
     * "email": "11@11.com", 必填
     * "name": "就比你屌协会",
     * "organization_id": 7,
     * "owerStuNum": "201430098024",
     * "password": "aaa" 必填
     * }
     */
    @PostMapping("/register")
    public Result register(@RequestBody @Valid Organization request, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.genFailResult(bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultGenerator.genSuccessResult(mOrgService.register(request));
    }


    /**
     * @api {post}  /org/login  组织登陆
     * @apiGroup org
     * @apiVersion 0.0.1
     * @apiExample json
     * {
     * "email": "11@11.com",
     * "password": "1231231231231231"
     * }
     */

    @PostMapping("/login")
    public Result login(@RequestBody @Valid OrgLoginForm loginForm, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.genFailResult(bindingResult.getFieldError().getDefaultMessage());
        }
        return ResultGenerator.genSuccessResult(mOrgService.login(loginForm), "组织登陆成功");
    }

    /**
     * @api {post}  /org/upload  上传excel文件(header 要用 multipart/form-data)
     * @apiGroup org
     * @apiVersion 0.0.1
     * @apiParam org_id    int    组织 id
     * @apiParam file  excel  文件（新建一个excel 在第一列写上一列的学号即可）
     */
    @PostMapping("/upload")
    public Result singleFileUpload(@RequestParam("file") MultipartFile file, @RequestParam("org_id") int org_id) throws Exception {
        if (file.isEmpty()) {
            throw new ServiceException("文件为空");
        }
        //获取文件名
        String fileName = file.getOriginalFilename();

        //验证文件名是否合格
        if (!ExcelUtils.validateExcel(fileName)) {
            throw new ServiceException("必须是Excel");
        }

        //进一步判断文件内容是否为空（即判断其大小是否为0或其名称是否为null）
        long size = file.getSize();
        if (StringUtils.isEmpty(fileName) || size == 0) {
            throw new ServiceException("文件不能为空");
        }
        List<String> stuNumList = ExcelUtils.readExcelValue(file);
        mOrgService.saveUsersFormFile(org_id, stuNumList);
        return ResultGenerator.genSuccessResult();
    }

    /**
     * @api {get}  /org/users/{org_id} 获取某个组织的全部用户信息
     * @apiVersion 0.0.1
     * @apiGroup org
     * @apiExample json
     * unRegisterUsers：是还没有通过app绑定我们系统的学生，弹个弹窗"请邀请您的成员登陆「在华广」app，即可添加入您的名单中"
     * {
     * "code": 200,
     * "data": {
     * "unRegisterUsers": [
     * "201430098001",
     * "201430098036",
     * "201430098037",
     * "201430098038"
     * ],
     * "users": [
     * {
     * "avatarUrl": "",
     * "bgUrl": "",
     * "clazz": "14软件工程1班",
     * "college": "计算机工程学院",
     * "description": "",
     * "email": "",
     * "grade": "2014",
     * "name": "曾雁",
     * "profession": "软件工程",
     * "sex": 1,
     * "studentNum": "201430098034",
     * "user_id": "2"
     * }
     * ]
     * },
     * "message": "SUCCESS"
     * }
     */
    @GetMapping("/users/{id}")
    public Result getMyUsers(@PathVariable("id") Integer org_id) throws Exception {
        return ResultGenerator.genSuccessResult(mOrgService.getMyUsers(org_id));
    }

    /**
     * @api {get}  /org/event/{org_id}  获取本组织所创建的活动
     * @apiVersion 0.0.1
     * @apiGroup org
     */
    @GetMapping("/event/{id}")
    public Result getEventCreateById(@PathVariable("id") Integer id) throws Exception {
        List<Event> events = mOrgService.getEventsById(id);
        return ResultGenerator.genSuccessResult(events);
    }

    @PostMapping("member")
    public Result addMember(@RequestBody @Valid MemberForm memberForm, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new ServiceException(bindingResult);
        }

        return ResultGenerator.genSuccessResult(mOrgService.addMember(memberForm.getOrgId(), memberForm.getStunum()));
    }

    @PostMapping("member/delete")
    public Result deleteMember(@RequestBody @Valid MemberForm memberForm, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new ServiceException(bindingResult);
        }
        return ResultGenerator.genSuccessResult(mOrgService.deleteMember(memberForm.getOrgId(), memberForm.getStunum()));
    }

    @GetMapping("member")
    public Result seachMember(@RequestParam("org_id") int org_id, @RequestParam("message") String message) throws Exception {
        List<User> list = mOrgService.searchMember(org_id, message);
        return ResultGenerator.genSuccessResult(list);
    }

    /**
     * @api {post}  /org/update/image  组织更新图片
     * @apiVersion 0.0.1
     * @apiGroup org
     * @apiParam org_id    int     组织id
     * @apiParam file  png,jpg 文件
     * @apiParam type  String  orgAvater 或者 orgBg
     */
    @PostMapping("/update/image")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file,
                               @RequestParam("org_id")  int org_id,
                               @RequestParam("type") String type) throws Exception {

        Organization organization = mOrgService.updateImage(org_id, file, ImageUtils.getImageType(type));
        return ResultGenerator.genSuccessResult(organization);
    }



    /**
     * @api {post}  /org/event  创建一个活动
     * @apiVersion 0.0.1
     * @apiGroup org
     * @apiParam org_id    int     组织id
     * @apiParam title    String     活动标题
     * @apiParam desc    String     活动描述
     * @apiParam detail    String     活动推文url 必须是url
     * @apiParam bg     file  推文背景图 （png,jpg 文件）
     *
     */
    @PostMapping("/create/event")
    public Result createEvent(@RequestParam("org_id") int org_id ,
                              @RequestParam("title") String title,
                              @RequestParam("desc") String desc,
                              @RequestParam("bg") MultipartFile bgFile ,
                              @RequestParam("detail") @URL String url
                              ) throws Exception {



        if (!mOrgService.hasOrg(org_id)) throw new ServiceException("没有找到此组织");

        Event event = new Event();
        event.setDescription(desc);
        event.setOrgId(org_id);
        event.setDetailUrl(url);
        event.setTitle(title);
        event = mOrgService.createEvent(event);
        event = mOrgService.updateEventImage(event.getId(), bgFile);

        return ResultGenerator.genSuccessResult(event);
    }



    /**
     * @api {get}  /org/{org_id}  获取一个组织的信息
     * @apiVersion 0.0.1
     * @apiGroup org
     */
    @GetMapping("/{org_id}")
    public Result getOrgInfo(@PathVariable int org_id) {
        return ResultGenerator.genSuccessResult(mOrgService.getOrgInfo(org_id));
    }

    /**
     * @api {get}   /org/event/peoples/{event_id}   获取参加活动的人员名单         
     * @apiVersion 0.0.1
     * @apiGroup org
     */
    @GetMapping("/event/peoples/{event_id}")
    public Result getPeoplesJoinInEvent(@PathVariable int event_id) {
        return ResultGenerator.genSuccessResult(mOrgService.getPeopleSignUpInEvent(event_id));
    }

    /**
     * @api {get}  /org/event/{event_id}/signup/excel  导出报名表成一个excel
     * @apiVersion 0.0.1
     * @apiGroup org
     */
    @GetMapping("/event/{event_id}/signup/excel")
    public Result createSignUpExcel(@PathVariable int event_id) throws Exception {
        return ResultGenerator.genSuccessResult(mOrgService.createSignUpExcel(event_id));
    }

    /**
     * @api {org}  /org/update/desc  更新描述
     * @apiVersion 0.0.1
     * @apiGroup org
     * @apiExample json
     * {
    "org_id": "2",
    "desc": "adfafdadfadfasdfadfasdfasdf"
    }
     *
     */
    @PostMapping("/update/desc")
    public Result updateDesc(@RequestBody @Valid UpdateOrgForm updateOrgForm , BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            throw new ServiceException(bindingResult);
        }
       return ResultGenerator.genSuccessResult(mOrgService.updateDesc(updateOrgForm.getOrg_id(),updateOrgForm.getDesc()));
    }
}